import { SYSTEM_LOGO_PATH, FIXED_LOGO_PATH } from "./constants.js";

const { SYSTEM, FIXED_SERVERS } = chrome.proxy.Mode;

/**
 * @param { String } selector
 * @returns { HTMLElement }
 */
export function $(selector) {
	return document.querySelector(selector);
}

/**
 * @param { String } selector
 * @returns { HTMLCollection }
 */
export function $$(selector) {
	return document.querySelectorAll(selector);
}

/**
 * @returns { String }
 */
export function generateNaoId() {
	let urlAlphabet =
		"useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";

	let nanoid = (size = 21) => {
		let id = "";
		let i = size;
		while (i--) {
			id += urlAlphabet[(Math.random() * 64) | 0];
		}
		return id;
	};

	return nanoid();
}

/**
 * @param {HTMLElement} ele
 */
export function toggleEle(ele) {
	const isHide = ele.classList.contains("hide");
	ele.classList.remove("hide", "show");

	if (isHide) {
		ele.classList.add("show");
	} else {
		ele.classList.add("hide");
	}
}

/**
 * 防抖函数
 * @param {Function} fn
 * @param {Number} delay
 * @returns
 */
export function debounce(fn, delay) {
	let timerId;
	return function () {
		clearTimeout(timerId);
		const args = Array.from(arguments);
		timerId = setTimeout(() => {
			fn.apply(this, args);
		}, delay);
	};
}

/**
 * @param {HTMLElement} contenteditable element
 */
export function parsePasteText(input) {
	input.addEventListener("paste", (event) => {
		const e = event || window.event;
		// 阻止默认粘贴
		e.preventDefault();
		// 粘贴事件有一个clipboardData的属性，提供了对剪贴板的访问
		// clipboardData的getData(fomat) 从剪贴板获取指定格式的数据
		const text =
			(e.originalEvent || e).clipboardData.getData("text/plain") ||
			prompt("在这里输入文本");
		// 插入
		document.execCommand("insertText", false, text);
	});
}

/**
 * @param {String} mode
 */
export function switchPopupIcon(mode) {
	switch (mode) {
		case SYSTEM:
			chrome.action.setIcon({ path: SYSTEM_LOGO_PATH });
			break;
		case FIXED_SERVERS:
			chrome.action.setIcon({ path: FIXED_LOGO_PATH });
			break;
	}
}
